package sg.edu.ntu.bloch.tictactoe.datasource.player;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

public class PlayerSourceFactory {
	private static PlayerSourceFactory factory;
	private static PlayerSource playerSource;
	private Type type;
	private static final Logger _log = Logger.getLogger(PlayerSourceFactory.class);
	public static enum Type {
		MEMORY {
			PlayerSource getInstance() {
				return new PlayerMapSource();
			}
		},
		FILE {
			PlayerSource getInstance() {
				return new PlayerFileSource();
			}
		};
		abstract PlayerSource getInstance();

		private static Map<String, Type> map;
		static {
			map = new HashMap<String, Type>();
			for (Type type : Type.values()) {
				map.put(type.toString(), type);
			}
		}

		public static Type fromString(String label) {
			if (label == null)
				return null;
			else
				return map.get(label.trim().toUpperCase());
		}
	}

	private PlayerSourceFactory() throws Exception {
		InputStream propSrc = ClassLoader
				.getSystemResourceAsStream("tictactoe.properties");
		Properties prop = new Properties();
		prop.load(propSrc);
		String _type = prop.getProperty("datasource.player.type");
		_log.debug("Type " + _type);
		type = Type.fromString(_type);
		playerSource = type.getInstance();
	}

	public static synchronized PlayerSourceFactory getInstance()
			throws Exception {
		if (factory == null)
			factory = new PlayerSourceFactory();
		return factory;
	}

	public PlayerSource getPlayerSourceInstance() {
		return playerSource;
	}
}
